package gvo.image.try2;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class ImageViewer extends JFrame {
	public ImageViewer(Image image) {
		setDefaultCloseOperation(HIDE_ON_CLOSE);
		setImage(image);
		setSize(200, 200);
		setVisible(true);
		
	}

	// Obtain the image from the producer.
	public ImageViewer(ImageProducer producer) {
		setImage(createImage(producer));
		setSize(200, 200);
		setVisible(true);
		
	}
	public void printPos(){
		Point p = this.getLocation();
		System.out.println("ImageViewer x="+ p.x + " y="+p.y);
	}
	public void repaintIt(Image image){
		setImage(image);
		this.repaint();
		this.setVisible(true);
	}
	

	public void paint(Graphics g) {
		// Make sure it appears just within the frame's insets.
		Insets insets = getInsets();
		g.drawImage(getImage(), insets.left, insets.top, this);
	}

	// Override Frame.imageUpdate - the implemention of ImageObserver.
	public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
		// Find out what has changed.
		boolean result = super.imageUpdate(img, infoflags, x, y, width, height);
		// See if the image is complete.
		if ((infoflags & ImageObserver.ALLBITS) != 0) {
			// Set the frame's size according to the image size.
			Insets insets = getInsets();
			// Include in the width and height the insets space required
			// for the frame's decoration.
			int newWidth = insets.left + width + insets.right;
			int newHeight = insets.top + height + insets.bottom;
			setSize(newWidth, newHeight);
		} else if ((infoflags & (ImageObserver.ABORT | ImageObserver.ERROR)) != 0) {
			System.err.println("Image error.");
		} else {
			// Ignore.
		}
		return result;
	}

	protected Image getImage() {
		return image;
	}

	protected void setImage(Image i) {
		image = i;
	}

	public static Image getImageFromUrl(String adr) {
		//adr = "http://ecx.images-amazon.com/images/I/51SIrw1LJyL._SL500_.jpg";
		Image img = null;
		try {
			URL url = new URL(adr);
			// Get the image
			img = ImageIO.read(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return img;
	}

	

	private Image image;
}